var G_Course = {
    '1':'小学奥数',
    '2':'小学数学',
    '3':'小学英语',
    '4':'小学语文',
    '5':'初中奥数',
    '6':'初一初二英语',
    '7':'初一初二数学',
    '8':'初一初二化学',
    '9':'初一初二物理',
    '10':'初一初二语文',
    '11':'初三英语',
    '12':'初三数学',
    '13':'初三物理',
    '14':'初三化学',
    '15':'初三语文',
    '16':'初中历史',
    '17':'初中地理',
    '18':'中考心里辅导',
    '19':'高中奥数',
    '20':'高一高二英语',
    '21':'高一高二数学',
    '22':'高一高二物理',
    '23':'高一高二化学',
    '24':'高一高二语文',
    '25':'高三英语',
    '26':'高三数学',
    '27':'高三物理',
    '28':'高三化学',
    '29':'高三语文',
    '30':'高中历史',
    '31':'高中地理',
    '32':'高考心里辅导',
    '33':'上海话',
    '34':'英语口语',
    '35':'新概念英语',
    '36':'牛津英语',
    '37':'托福',
    '38':'雅思',
    '39':'商务英语',
    '40':'日语',
    '41':'韩语',
    '42':'德语',
    '43':'法语',
    '44':'意大利语',
    '45':'西班牙语',
    '46':'阿拉伯语',
    '47':'俄语',
    '48':'葡萄牙语',
    '49':'钢琴',
    '50':'电子琴',
    '51':'小提琴',
    '52':'小号',
    '53':'芭蕾舞',
    '54':'吉它',
    '55':'民族舞',
    '56':'单簧管',
    '57':'萨克斯',
    '58':'声乐',
    '59':'大号',
    '60':'长笛',
    '61':'琵琶',
    '62':'手风琴',
    '63':'古筝',
    '64':'古琴',
    '65':'大提琴',
    '66':'打击乐',
    '67':'圆号',
    '68':'高等数学',
    '69':'网球',
    '70':'乒乓球',
    '71':'游泳',
    '72':'围棋',
    '73':'中国画',
    '74':'国际象棋',
    '75':'羽毛球',
    '76':'中国象棋',
    '77':'卡通画',
    '78':'书法',
    '79':'美术',
    '80':'跆拳道',
    '81':'空手道'
};
setCenter = function(ele) {
    if (!ele instanceof jQuery) return false;
    var w = jQuery(window);
    var config = {
        left: ((w.width() - ele.outerWidth()) / 2) + w.scrollLeft(),
        top: ((w.height() - ele.outerHeight()) / 2) + w.scrollTop()
    };
    ele.css({left:config.left, top:config.top});
    delete w,config;
}
function move(e, ele, win) {
    ele.css({cursor:'move'});
    var isie = jQuery.browser.msie;
    if (isie) {
        document.body.onselectstart = function() {
            return false;
        }
    }
    e = isie ? window.event : e;
    var x = e.clientX;
    var y = e.clientY;

    var w = x - parseInt(win[0].offsetLeft);
    var h = y - parseInt(win[0].offsetTop);

    document.body.setCapture;
    document.onmousemove = function(e) {
        e = isie ? window.event : e;
        var x = e.clientX;
        var y = e.clientY;
        win.css({left:x - w, top:y - h});
    };
    document.onmouseup = function(e) {
        if (isie) {
            document.body.onselectstart = function() {
                return true;
            };
        }
        ;
        document.body.releaseCapture;
        document.onmousemove = null;
        document.onmouseup = null;
        ele.css({cursor:'default'});
    };
}

var loading = function() {
    var html = '<div id="loading" class="loading"><s></s><div class="loading_c">正在处理请求，请等候...</div></div>';
    $('body').append(html);
    loading.loadbar = $('#loading');
}
loading.has = false;
loading.show = function() {
    if (!loading.loadbar) loading();
    setCenter(loading.loadbar);
    loading.loadbar.css({visibility:'visible', opacity:0});
    loading.loadbar.animate({opacity:1}, 100);
    loading.has = true;
}
loading.hide = function() {
    if (!loading.loadbar) return false;
    loading.loadbar.animate({opacity:0}, 100, null, function() {
        loading.loadbar.css({visibility:'hidden'});
    });
    loading.has = false;
}

var panelList = [];
panel = function() {
    panelList.push(this);
    var id = panel.getId();
    this.id = (id.key + '').replace('.', '');
    this.guidIndex = id.index;
    this.body = jQuery('body:eq(0)');
    this.container = '<div id="panel_w_' + this.id + '" class="panel_w"><div class="panel_c"><div class="panel_t"><a class="panel_s" href="javascript:void(0)"></a><h2>标题</h2></div><div class="panel_cont"></div><div class="panel_b"></div></div></div>';
    if (!panel.mask) {
        panel.mask = '<div id="panel_m" class="panel_m">' + (($.browser.version == '6.0') ? '<iframe></iframe>' : '') + '</div>';
        this.trace = panel.mask + this.container;
    } else {
        this.trace = this.container;
    }

    this.body.prepend(this.trace);
    this.title = null;
    this.content = null;
    this.buttons = null;
    this.close = null;
    this.width = 200;

    this.init();
}
panel.guid = [];
panel.zindex = 1;
panel.maskDisplay = function(method) {
    if (method == 'hide') {
        for (var i = 0; i < panel.guid.length; i++) {
            if (panel.guid[i].display == 'show')
                return;
        }

        panel.mask.animate({opacity:0}, 150, null, function() {
            panel.mask.css({visibility:'hidden'});
        });
    } else if (method == 'show') {
        if (panel.mask.css('visibility') == 'visible') {
            return;
        }
        panel.mask.css({visibility:'visible', opacity:0});
        panel.mask.animate({'opacity':0.5}, 150);
    }
}

panel.getId = function() {
    var r = Math.random();
    var len = panel.guid.length;
    // 确定唯一性
    while (panel.keyExists(r)) {
        r = Math.random();
    }
    panel.guid[len] = {
        key:r,
        display:'hide'
    };
    return {
        key:r,
        index:len
    };
}

panel.keyExists = function(k) {
    for (var i = 0; i < panel.guid.length; i++) {
        if (panel.guid[i].key == k) {
            return true;
        }
    }
    return false;
}

panel.prototype = {
    init : function() {
        var content, title;
        panel.mask = this.body.find('#panel_m');

        this.trace = this.body.find('#panel_w_' + this.id);
        content = this.trace.children('.panel_c');
        title = content.children('.panel_t');
        this.title = title.children('h2');
        this.close = title.children('a.panel_s');
        this.content = content.children('div.panel_cont');
        this.buttons = content.children('div.panel_b');
        var _self = this;
        // 绑定移动
        title.mousedown(function(e) {
            move(e, title, _self.trace);
        });

        this.close.click(function() {
            _self.setDisplay('hide'); //TODO
            return false;
        });

        if (panel.guid.length == 1) {
            this.initMaskStyle();// TODO
        }
        //TODO 这里是否需要优化,考虑使用fixed
        $(window).bind('scroll',
                function() {
                    _self.setCenter();
                }).resize(function() {
            _self.initMaskStyle();
            _self.setCenter();
        });
    },
    initMaskStyle: function() {
        var win = jQuery(window);
        var width = (this.body.width() < win.width() ? win.width() : this.body.width());
        panel.mask.css('display', 'none');
        var height = win.height();
        panel.mask.css('display', 'block');
        panel.mask.width(width);
        panel.mask.height(height);
        panel.mask.css('opacity', 0.5);
    },
    setCenter:function() {
        var w = jQuery(window);
        var width = ((this.body.width() - this.trace.outerWidth()) / 2) + w.scrollLeft();
        var height = ((w.height() - this.trace.outerHeight()) / 2) + w.scrollTop();
        var top = w.scrollTop();
        this.trace.css({
            left:width,
            top:height
        });
        panel.mask.css('top', top);//TODO 考虑使用fixed
    },
    setDisplay: function(method) {
        var _self = this;
        if (method == 'hide' || method == 'show') {
            panel.mask.stop(false, true);
            this.trace.stop(false, true);
            panel.guid[this.guidIndex].display = method;
            panel.maskDisplay(method);
            if (method == 'hide') {
                this.trace.animate({
                    opacity:0
                }, 150, null, function() {
                    $(this).css('visibility', 'hidden');
                    try {
                        _self.onHide();
                    } catch(e) {
                    }
                });
                //TODO 从dom中删除元素
                // this.trace.remove();
            } else if (method == 'show') {
                this.setCenter();
                this.trace.css({
                    visibility:'visible',
                    opacity:0
                });
                this.trace.animate({
                    opacity:1
                }, 150, function() {
                    try {
                        _self.onShow();
                    } catch(e) {
                    }
                })
            }
        }
    },
    setContent:function(title, content, buttons) {
        var btnStr = '';
        if (title) this.title.html(title);
        if (content) this.content.html(content);
        if (buttons) {
            for (var i = 0; i < buttons.length; i++) {
                btnStr += buttons[i].html + (((i + 1) == buttons.length) ? '' : ' ');
                this.buttons.html(btnStr);
                this.bindEvent(buttons);//TODO
            }
        }
        this.setCenter();
    },
    setTitle:function(title) {
        if (title)
            this.title.html(title);
    },
    appendContent: function(content) {
        this.content.html('');
        this.content.append(content);
        this.setCenter();
    },
    bindEvent:function(buttons) {
        var a = this.buttons.find('a'), idx, _self = this;
        a.click(function() {
            idx = a.index(this);
            if (buttons[idx].callback == 'close') {
                _self.setDisplay('hide');
            } else {
                buttons[idx].callback();
                return false;
            }
        })
    },
    setWidth: function(width) {
        this.trace.find('div.panel_c').width(width);
        this.setCenter();
    },
    getButton: function(text, color, callback) {
        if (!text || !color) return null;
        var html;
        if (color == 'blue' || color == 'yellow' || color == 'gray') {
            color = /^.?/.exec(color);
            html = '<a href="javascript:void(0)" class="but b_2_' + color + '"><u></u>' + text + '</a>';
        } else if (color == 'href') {
            html = '<a href="javascript:void(0)" class="txthref">' + text + '</a>';
        }
        return {
            html:html,
            callback:callback
        }
    },
    setDefaultCloseDisplay:function(method) {
        var close = this.getThis().find('a.panel_s');//TODO
        if (method = 'hide') {
            close.hide();
        }
        else {
            close.show();
        }
        delete close;
    },
    setDefaultButtonDisplay:function(m) {
        if (m == 'hide') {
            this.buttons.hide();
        } else {
            this.buttons.show();
        }
        this.setCenter();
    },
    getThis:function() {
        return this.trace;
    }
}

var ipanel = panel.prototype;
InfoPanel = function() {
    var ip = new panel();
    ipanel = ip;
    ip.setWidth(350);
    ip.setContent('系统提示', null, [ipanel.getButton('确定', 'gray', 'close')]);
    ip.getThis().addClass('panel_i');

    ip.onShow = function() {
        try {
            InfoPanel.onShow();
        } catch(e) {
        }
    }
    ip.onHide = function() {
        try {
            InfoPanel.onHide();
        } catch(e) {
        }
    }
}
InfoPanel._timer = null;
InfoPanel.hasInit = false;
/**
 *
 * @param menu 提示的内容
 * @param info i,o,e
 * @param time 过期时间
 * @param btn 可以添加按钮
 * ipanel.getButton('text','color',callback)
 * @param m 内容的样式
 */
InfoPanel.show = function(menu, info, time, btn, m) {
    if (InfoPanel.hasInit == false) {
        InfoPanel();
        InfoPanel.hasInit = true;
    }
    var info = info || "i";
    ipanel.setContent(null, '<div class="p_info clearfix"><u class="msg m_1_' + info + '"></u><p class="p_info_c ' + (m ? '' : 'm10') + ' ml15">' + menu + '</p></div>', ((btn) ? btn : [ipanel.getButton('确定', 'gray', 'close')]));
    ipanel.setDisplay('show');
    if (time && /^[0-9]*$/.test(time)) {
        InfoPanel._timer = window.setTimeout(function() {
            window.clearTimeout(InfoPanel._timer);
            InfoPanel.hide();
        }, time)
    }
}

InfoPanel.hide = function() {
    ipanel.setDisplay('hide');
    window.clearTimeout(InfoPanel._timer);
}

var UnivWin = function(cb) {
    this.win = new panel('大学选择', null, null);
    var w = this.win;
    w.setTitle('大学选择');
    w.setWidth(650);
    if (cb) {
        this.cb = cb;
    }
    this.init();
}
var AjaxRequest = function(url, data, cb) {
    $.ajax({
        url:url,
        dataType:'json',
        data:data,
        type:'POST',
        success:function(json) {
            cb(json);
        }
    });
};
// 全局变量，用于缓存省份信息和学校信息
var G_AS = {
    provinceUrl:path + '/area/get', // province url
    univUrl:path + '/school/get', // university url
    /**
     *  [{c:provinceCode, n:provinceName}]
     * @param data 需要传递的参数，目前只有tp属性，且tp=0,data.tp
     * @param callback
     */
    getProvince:function(data, callback) {
        if (G_AS.province) {
            callback(G_AS.province);
        } else {
            $.ajax({
                url:UnivWin.purl,
                dataType:'json',
                data:data,
                type:'POST',
                success:function(json) {
                    G_AS.province = json;
                    callback(json);
                }
            });
        }
    },
    /**
     *
     * @param data 需要传递的参数，包括p(省份编号)data.p
     * @param cb
     */
    getUnivs:function(data, cb) {
        // 声明变量用于存放大学信息
        // G_AS.univs={p1100:[{c:1101,name:'beijingdaxue'},{c:1102,name:'qinghuadaxue'}]}
        if (!G_AS.univs) {
            G_AS.univs = {};
        }
        var p = 'p' + data.p;
        if (G_AS.univs[p]) {
            cb(G_AS.univs[p]);
        } else {
            data.tp = 0;
            $.ajax({
                url:UnivWin.uurl,
                dataType:'json',
                data:data,
                type:'POST',
                success:function(json) {
                    G_AS.univs[p] = json;
                    cb(json);
                }
            });
        }
    },
    /**
     * 关联一个省有哪些城市
     * cities={pid:{
     *      c:provinceId,
     *      cities:[{c:citycode, n:cityname}]
     *  }
     * }
     * @param data
     * @param cb
     */
    getCities:function(data, cb) {
        if (!G_AS.cities) {
            G_AS.cities = {};
        }
        var p = 'p' + data.pid;
        if (G_AS.cities[p]) {
            cb(G_AS.cities[p].cities);
        } else {
            G_AS.cities[p] = {};
            data.tp = 1;
            $.ajax({
                url:G_AS.provinceUrl,
                dataType:'json',
                data:data,
                type:'POST',
                success:function(cities) {
                    G_AS.cities[p]['cities'] = cities;
                    cb(cities);
                }
            });
        }
    },

    /**
     * 获取dist
     * G_AS.dists={
     *     cid:{
     *         dists:[{c:'',n:''}]
     *     }
     * }
     * @param data
     * @param cb
     */
    getDists:function(data, cb) {
        if (!G_AS.dists) {
            G_AS.dists = {};
        }
        var k = 'c' + data.pid;
        if (G_AS.dists[k]) {
            cb(G_AS.dists[k].dists);
        } else {
            G_AS.dists[k] = {};
            data.tp = 2;
            AjaxRequest(G_AS.provinceUrl, data, function(dists) {
                G_AS.dists[k].dists = dists;
                cb(dists);
            });
        }
    },
    /**
     * highschool={
     *     cityid:{
     *         schools:[{c:'',n:''}]
     *     }
     * }
     * @param data
     * @param cb
     */
    getHighSchool:function(data, cb) {
        var p = 'p' + data.p;
        var ct;//current type
        switch(data.tp){
            case 1:  //high school
                if(!G_AS.highSchool) {
                    G_AS.highSchool = {};
                }
                ct =  G_AS.highSchool;
                break;
            case 2: //college
                if(!G_AS.college) {
                    G_AS.college = {};
                }
                ct =  G_AS.college;
                break;
            case 3: // junior
                if(!G_AS.junior) {
                    G_AS.junior= {};
                }
                ct =  G_AS.junior;
                break;
        }
        /*if (!G_AS.highSchool) {
            G_AS.highSchool = {};
        } */

        if (ct[p]) {
            cb(ct[p].schools);
        } else {
            if (!data.tp) {
                data.tp = 1;
            }
            ct[p] = {};
            AjaxRequest(G_AS.univUrl, data, function(schools) {
                ct[p].schools = schools;
                cb(schools);
            });
        }
    }
};

UnivWin.univs = {};
UnivWin.template = TrimPath.parseTemplate('{for d in list}<li><a href="javascript:void(0);" id="${d.c}" title="${d.n}">${d.n}</a></li>{/for}');
UnivWin.pTpl = '<div class="univ"><ul class="clearfix"></ul></div><div class="univs"><ul></ul></div>';
UnivWin.purl = path + '/area/get'; // province url
UnivWin.uurl = path + '/school/get'; // university url
UnivWin.requestProvince = function(data, callback) {
    G_AS.getProvince(data, callback);
}
UnivWin.requestUnivs = function(data, univC, cb) {
    univC.html('loading...');
    G_AS.getUnivs(data, function(univs) {
        var us = UnivWin.template.process({list:univs});
        univC.html(us);
        univC.find('a').click(function(e) {
            if (cb) {
                univC.find('a').removeClass('current');
                $(this).addClass('current');
                cb(this);
            }
        });
    });
}
UnivWin.prototype = {
    init:function() {
        var _self = this;
        _self.win.appendContent(UnivWin.pTpl);
        // 存放省的容器
        this.provC = _self.win.trace.find('.univ>ul');
        //存放大学的容器
        this.univC = _self.win.trace.find('.univs>ul');
        this.provC.html('loading...');
        this.univC.html('loading...');
        UnivWin.requestProvince({tp:'0'}, function(json) {
            var prov = UnivWin.template.process({list:json});
            _self.provC.html(prov);
            _self.provC.find('a:eq(0)').addClass('current');
            _self.provC.find('a').click(function(e) {
                _self.provC.find('a').removeClass('current');
                $(this).addClass('current');
                UnivWin.requestUnivs({p:this.id}, _self.univC, _self.cb);
            });
            UnivWin.requestUnivs({p:json[0].c}, _self.univC, _self.cb);
        });
        this.win.setDisplay('show');
    },
    show:function() {
        this.win.setDisplay('show');
    },
    hide:function() {
        this.win.setDisplay('hide');
    }
}

HighWin = function(cb) {
    this.win = new panel('选择', null, null);
    var w = this.win;
    w.setTitle('高中选择');
    w.setWidth(650);
    if (cb) {
        this.cb = cb;
    }
    this.tp=1;
    this.init();
}
HighWin.template = TrimPath.parseTemplate('{for d in list}<li><a href="javascript:void(0);" id="${d.c}"{if d.s!=null || defined("s")} s="1"{/if} title="${d.n}">${d.n}</a></li>{/for}');
HighWin.pTpl = '<div class="hw_provs"><ul class="clearfix"></ul></div><div class="hw_cities"><ul></ul></div><div class="hw_dists"><ul></ul></div><div class="hw_highschs"><ul></ul></div>';

HighWin.prototype = {
    init:function() {
        this.win.appendContent(HighWin.pTpl);
        var trace = this.win.trace;
        this.provC = trace.find('.hw_provs>ul');
        this.citiesC = trace.find('.hw_cities>ul');
        this.distsC = trace.find('.hw_dists>ul');
        this.highschC = trace.find('.hw_highschs>ul');
        trace = null;
        var _self = this;

        G_AS.getProvince({tp:'0'}, function(provs) {
            _self.provC.html(HighWin.template.process({list:provs}));
            _self.provC.find('a:eq(0)').addClass('current');
            _self.provC.find('a').click(function(e) {
                var a = $(this);
                _self.provC.find('a').removeClass('current');
                a.addClass('current');
                _self.getCities(a.attr('id'), a.attr('s'));
            });
            _self.getCities(provs[0].c, provs[0].s);
        });

        this.win.setDisplay('show');
    },
    getCities: function(provinceId, specific) {
        var _self = this;
        _self.citiesC.html('loading...');
        _self.highschC.html('loading...');
        if(!specific) {
            _self.distsC.html('loading...');
        }
        G_AS.getCities({tp:'1',pid:provinceId}, function(cities) {
            if (specific) {
                _self.citiesC.html(HighWin.template.process({list:cities,s:true}));
            } else {
                _self.citiesC.html(HighWin.template.process({list:cities}));
            }
            _self.citiesC.find('a:eq(0)').addClass('current');
            _self.citiesC.find('a').click(function(e) {
                var a = $(this);
                _self.citiesC.find('a').removeClass('current');
                a.addClass('current');
                var sp = a.attr('s');
                if (sp) {
                    _self.getHighschool(a.attr('id'));
                } else {
                    _self.getDists(a.attr('id'));
                }
            });
            // 如果是特区，没有dist信息
            if (specific) {
                _self.distsC.hide();
                if(cities.length > 0) {
                    _self.getHighschool(cities[0].c);
                }
            } else {
                _self.getDists(cities[0].c);
            }
        });
    },
    getHighschool:function(distid) {
        var _self = this;
        _self.highschC.html('loading...');
        G_AS.getHighSchool({p:distid,tp:_self.tp}, function(schools) {
            if (schools.length == 0) {
                _self.highschC.html('');
            } else {
                _self.highschC.html(HighWin.template.process({list:schools}));
                _self.highschC.find('a').click(function(e) {
                    if (_self.cb) {
                        var a = $(this);
                        _self.cb(a);
                    }
                });
            }
        });
    },
    getDists:function(cityId) {
        var _self = this;
        _self.distsC.show();
        G_AS.getDists({pid:cityId}, function(dists) {
            _self.distsC.html(HighWin.template.process({list:dists}));
            _self.distsC.find('a:eq(0)').addClass('current');
            _self.distsC.find('a').click(function(e) {
                var a = $(this);
                _self.distsC.find('a').removeClass('current');
                a.addClass('current');
                _self.getHighschool(this.id);
            });
            if (dists.length > 0) {
                _self.getHighschool(dists[0].c);
            } else {
                _self.highschC.html('');
            }
        });
    },
    show:function() {
        this.win.setDisplay('show');
    },
    hide:function() {
        this.win.setDisplay('hide');
    }
}

JuniorWin = function(cb) {
    this.win = new panel('选择', null, null);
    var w = this.win;
    w.setTitle('初中选择');
    w.setWidth(650);
    if (cb) {
        this.cb = cb;
    }
    this.tp = 3;
    if (!JuniorWin.init) {
        JuniorWin.init = true;
        jQuery.extend(JuniorWin.prototype, HighWin.prototype);
    }
    this.init();
}

CollegeWin = function(cb) {
    this.win = new panel('选择', null, null);
    var w = this.win;
    w.setTitle('初中选择');
    w.setWidth(650);
    if (cb) {
        this.cb = cb;
    }
    this.tp = 2;

    if (!CollegeWin.init) {
        CollegeWin.init = true;
        jQuery.extend(CollegeWin.prototype, HighWin.prototype);
    }
    this.init();
}

Subject = function(cb){
    this.win = new panel('课程选择', null, null);
    var w = this.win;
    w.setTitle('课程选择');
    w.setWidth(400);
    if(cb){
        this.cb = cb;
    }
    this.init();
}
Subject.prototype = {
    init:function(){
        var s = '<ul id="w_course" class="clearfix">';
        for(c in G_Course) {
            s += '<li><a href="javascript:void(0);" id="'+c+'">'+G_Course[c]+'</a></li>';
        }
        s+='</ul>'
        this.win.appendContent(s);
        var _self = this;
        this.win.trace.find('#w_course a').click(function(e){
            if(_self.cb) {
                _self.cb($(this));
            }
        });
        delete s;
        this.win.setDisplay('show');
    },
    show:function(){
        this.win.setDisplay('show');
    },
    hide:function(){
        this.win.setDisplay('hide');
    }
}
